# -*- coding: utf-8 -*-
import json
from flask_admin import BaseView, expose
from flask import jsonify
from flask import flash, url_for, redirect, request, current_app
from flask_wtf import FlaskForm
from wtforms import TextAreaField
from adminApp.views import MyCusView
from adminApp.extensions import db,redis_store
from adminApp.models import Idc,Machine,AqyBandWidth95
from sqlalchemy import func
from datetime import datetime,timedelta
'''
展示速率曲线图
'''

class ShowBandWidth95View(MyCusView):

    @expose('/', methods=('GET', 'POST'))
    def index(self):
        # 列出机房
        idcs = [(r.id,r.name,r.machines.count()) for r in db.session.query(Idc).all()]
        # 默认将只查询系统==centos 的机器
        # 查询参数：机房ID(多选)，设备标志(多选),爱奇艺ID(多选)
        marks = db.session.query(Machine.man_mark, func.count('*').label('c'))\
            .filter(Machine.is_centos == True).filter(Machine.man_mark!=None).group_by(Machine.man_mark)
        result = []
        idc_ids = []
        machine_marks = []
        deviceids = ''
        timepoint = ''
        # aqy_band_width95_backup_210104
        if request.method=='POST':
            idc_ids = request.values.getlist("chkidc_id")
            machine_marks = request.values.getlist("machine_marks")
            deviceids = request.form.get('deviceids')
            timepoint = request.form.get('inp_day_chart')
            tem_timepoint = timepoint.split(' - ')
            start_time = datetime.strptime(tem_timepoint[0].strip(), '%Y-%m-%d')
            # 加一天 等于选择日期的夜里23:59:59
            end_time = datetime.strptime(tem_timepoint[1].strip(), '%Y-%m-%d')+timedelta(days=1)

            # 查询主机
            q = db.session.query(Machine.id, Machine.hostname, Machine.aqy_device_id).filter(Machine.is_centos == True)
            if idc_ids:
                idc_ids=[int(k) for k in idc_ids]
                q = q.filter(Machine.idc_id.in_(idc_ids))
            if machine_marks:
                q = q.filter(Machine.man_mark.in_(machine_marks))
            if deviceids:
                q = q.filter(Machine.aqy_device_id.in_(deviceids.split(',')))
            machines = q.order_by(Machine.hostname).all()

            for k in machines:
                # 根据设备Id查询 5分钟带宽速率值
                finds = db.session.query(AqyBandWidth95.Unix_time,AqyBandWidth95.MbpsSent)\
                    .filter(AqyBandWidth95.machine_id==k.id)\
                    .filter(AqyBandWidth95.Unix_time>=start_time)\
                    .filter(AqyBandWidth95.Unix_time<=end_time).all()
                v95 = [k.MbpsSent for k in finds]
                v95.sort()
                bd95val = 0
                if v95:
                    ixx95 = round(len(v95) * 0.95)
                    if ixx95-1>0:
                        bd95val=round(v95[ixx95 - 1] / 1024 / 1024)
                result.append(dict(info=[k.id, k.hostname, k.aqy_device_id, len(finds)],
                                   bd95val= bd95val,
                                   data_x=','.join(["'{}'".format(datetime.strftime(k.Unix_time, '%Y-%m-%d %H:%M:%S')) for k in finds]),
                                   data_y=','.join([str(round(k.MbpsSent/1024/1024)) for k in finds])))
            # 计算95值
            # print(result)
        # tda=''
        # tdb=''
        # tdc = ''
        # tdd = ''
        # tde = ''
        # tdf = ''
        # daa =[]
        # dab = []
        # dac = []
        # with open('1B4B031C971FD9BE.json','r') as f:
        #     ra,rb = [],[]
        #     for k in json.load(f).get('aqysnmp'):
        #         md=datetime.strptime(k[0].strip(), '%Y-%m-%d_%H:%M:%S')
        #         if md>=datetime.strptime('2020-12-08', '%Y-%m-%d') and md<=datetime.strptime('2020-12-31', '%Y-%m-%d'):
        #             ra.append("'{}'".format(k[0][:10]))
        #             rb.append(str(round(int(k[2])/1024/1024,2)))
        #             daa.append(round(int(k[2])/1024/1024,2))
        #     tda = ','.join(ra)
        #     tdb = ','.join(rb)
        # with open('1B4B031C971FD9BE-zabbix.json','r') as f:
        #     ra,rb = [],[]
        #     for k in json.load(f):
        #         md = datetime.strptime(k[0].strip(), '%Y-%m-%d %H:%M:%S')
        #         if md >= datetime.strptime('2020-12-08', '%Y-%m-%d') and md <= datetime.strptime('2020-12-31',
        #                                                                                          '%Y-%m-%d'):
        #             ra.append("'{}'".format(k[0][:10]))
        #             rb.append(str(round(int(k[1])/1024/1024,2)))
        #             dab.append(round(int(k[1]) / 1024 / 1024, 2))
        #     tdc = ','.join(ra)
        #     tdd = ','.join(rb)
        # with open('1B4B031C971FD9BE-ser.json','r') as f:
        #     ra,rb = [],[]
        #     for k in json.load(f):
        #         # ra.append("'{}'".format(k[0][:10]))
        #         # rb.append(str(round(int(k[1])/1024/1024,2)))
        #         dac.append(k)
        #     tde = ','.join(ra)
        #     tdf = ','.join(rb)
        # # calc 95
        # daa.sort()
        # dab.sort()
        # dac.sort()
        # print(len(daa),len(dab),len(dac))
        # caa = round(len(daa) * 0.95)
        # cab = round(len(dab) * 0.95)
        # cac = round(len(dac) * 0.95)
        # caa_val = daa[caa - 1]
        # cab_val = dab[cab - 1]
        # cac_val = dac[cac - 1]
        # print(caa,cab,cac)
        # print(caa_val, cab_val,cac_val)
        # return self.render('machine/show_bandwidth95.html', idcs=idcs, marks=marks, idc_ids=idc_ids,
        #                    machine_marks=machine_marks, deviceids=deviceids,
        #                    range_day=timepoint, result=result, tda=tda,tdb=tdb, tdc=tdc,tdd=tdd)
        return self.render('machine/show_bandwidth95.html', idcs=idcs, marks=marks, idc_ids=idc_ids,
                           machine_marks=machine_marks, deviceids=deviceids,
                           range_day=timepoint, result=result)

    @expose('/search_result', methods=('GET', 'POST'))
    def search_result(self):

        result = dict()
        idc_ids = request.values.getlist("chkidc_id")
        machine_marks = request.values.getlist("machine_marks")
        deviceids = request.args.get('deviceids')
        timepoint = request.args.get('inp_minuter')

        if timepoint:
            try:
                timepoint = datetime.strptime(timepoint, '%Y-%m-%d %H:%M:%S')
            except:
                result['code'] = 400
                result['msg'] = '时间点参数错误，不能转换为日期'
        else:
            result['code'] = 400
            result['msg'] = '缺少时间点参数错误，请选择'
        if not result.get('code'):
            # 默认将只查询系统==centos 的机器
            # 查询参数：机房ID(多选)，设备标志(多选),爱奇艺ID(多选)
            q = db.session.query(Machine.id,Machine.hostname,Machine.aqy_device_id).filter(Machine.is_centos==True)
            if idc_ids:
                q = q.filter(Machine.idc_id.in_(idc_ids))
            if machine_marks:
                q = q.filter(Machine.man_mark.in_(machine_marks))
            if deviceids:
                q = q.filter(Machine.aqy_device_id.in_(deviceids.split(',')))
            machines = q.order_by(Machine.hostname).all()
            # 遍历ID 获取该设备在该时间点的带宽速率，若获取多个则取其中一个
            # 时间 以该时间点为中心 上下各增加减少 2.5分钟 取时间区域
            timepoint_start = timepoint- timedelta(seconds=150)
            timepoint_end = timepoint+ timedelta(seconds=150)
            find_data = []
            find_machine_data = []
            cant_find_data = []
            find_multi_data = []
            will_calc_data = []
            for k in machines:
                will_calc_data.append([k.id,k.hostname,k.aqy_device_id])
                find = db.session.query(AqyBandWidth95.MbpsSent).filter(AqyBandWidth95.machine_id==k.id)\
                    .filter(AqyBandWidth95.Unix_time>=timepoint_start).filter(AqyBandWidth95.Unix_time<=timepoint_end).all()
                if find:
                    if len(find)>1:
                        find_multi_data.append([k.id, k.hostname, k.aqy_device_id, len(find)])
                        temp=0
                        for r in find:
                            if r.MbpsSent>temp:
                                temp=r.MbpsSent
                        # find_data.append(temp)
                        find_machine_data.append([k.id, k.hostname, k.aqy_device_id, temp])
                    else:
                        # find_data.append(find.MbpsSent)
                        find_machine_data.append([k.id, k.hostname, k.aqy_device_id, find[0].MbpsSent])
                else:
                    cant_find_data.append([k.id,k.hostname,k.aqy_device_id])
            # 从 find_data 中 按 95取值，去掉最大的5%的点然后取最大值
            # 生序排列
            # find_data.sort()
            find_machine_data.sort(key=lambda x:x[3])
            if find_machine_data:
                bandwidth_95_value = find_machine_data[round(len(find_machine_data)*0.95)-1][3]
            else:
                bandwidth_95_value ='以该时间点获取数据为空'
            result['code'] = 200
            result['msg'] = dict(will_calc_data=will_calc_data,find_machine_data = find_machine_data,
                                 cant_find_data=cant_find_data,find_multi_data=find_multi_data,bd95val=bandwidth_95_value)
        print(result)
        return jsonify(result)